<template>
  <div class="roles-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="searchForm.roleCode" placeholder="请输入角色编码" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加角色
      </el-button>
    </div>

    <!-- 角色列表 -->
    <el-table
      v-loading="loading"
      :data="roleList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="roleName" label="角色名称" width="120" align="center" />
      <el-table-column prop="roleCode" label="角色编码" width="120" align="center" />
      <el-table-column prop="description" label="描述" min-width="200" align="center" />
      <el-table-column prop="createdTime" label="创建时间" width="180" align="center" />
      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="success" link @click="handleAssignMenus(row)">
            分配菜单
          </el-button>
          <el-button
            type="danger"
            link
            @click="handleDelete(row)"
            v-if="row.roleCode !== 'ADMIN'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加角色' : '编辑角色'"
      width="500px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input
            v-model="roleForm.roleCode"
            placeholder="请输入角色编码"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配菜单对话框 -->
    <el-dialog
      v-model="menuDialogVisible"
      title="分配菜单"
      width="600px"
    >
      <el-form label-width="80px">
        <el-form-item label="角色">
          <span>{{ currentRole.roleName }} ({{ currentRole.roleCode }})</span>
        </el-form-item>
        <el-form-item label="菜单">
          <el-tree
            ref="menuTreeRef"
            :data="menuTree"
            :props="{ label: 'name', children: 'children' }"
            show-checkbox
            node-key="id"
            :default-checked-keys="selectedMenus"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="menuDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveMenus">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getRoleList, 
  addRole, 
  updateRole, 
  deleteRole,
  getRoleMenus,
  assignRoleMenus,
  getMenuTree
} from '@/api/system'
import request from '@/utils/request'

// 搜索表单
const searchForm = reactive({
  roleName: '',
  roleCode: ''
})

// 分页参数
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)

// 角色列表数据
const roleList = ref([])

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    const { data } = await getRoleList(params)
    roleList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchRoleList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.roleName = ''
  searchForm.roleCode = ''
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRoleList()
}

// 页码改变
const handleCurrentChange = (val) => {
  page.value = val
  fetchRoleList()
}

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const roleFormRef = ref(null)
const roleForm = reactive({
  roleName: '',
  roleCode: '',
  description: ''
})

// 表单校验规则
const roleRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' }
  ]
}

// 添加角色
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(roleForm, {
    roleName: '',
    roleCode: '',
    description: ''
  })
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(roleForm, row)
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!roleFormRef.value) return
  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addRole(roleForm)
          ElMessage.success('添加成功')
        } else {
          await updateRole(roleForm.id, roleForm)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchRoleList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该角色吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRole(row.id)
      ElMessage.success('删除成功')
      fetchRoleList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 菜单相关
const menuDialogVisible = ref(false)
const currentRole = ref({})
const menuTree = ref([])
const selectedMenus = ref([])
const menuTreeRef = ref(null)

// 获取菜单树
const fetchMenuTree = async () => {
  try {
    const { data } = await getMenuTree()
    menuTree.value = data
  } catch (error) {
    console.error('获取菜单树失败:', error)
    ElMessage.error('获取菜单树失败')
  }
}

// 获取角色菜单
const fetchRoleMenus = async (roleId) => {
  try {
    const { data } = await getRoleMenus(roleId)
    selectedMenus.value = data
  } catch (error) {
    console.error('获取角色菜单失败:', error)
    ElMessage.error('获取角色菜单失败')
  }
}

// 分配菜单
const handleAssignMenus = async (row) => {
  currentRole.value = row
  await fetchRoleMenus(row.id)
  menuDialogVisible.value = true
}

// 保存菜单分配
const handleSaveMenus = async () => {
  try {
    const checkedKeys = menuTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()
    const menuIds = [...checkedKeys, ...halfCheckedKeys]
    
    // Call the correct API endpoint for assigning menus
    await assignRoleMenus(currentRole.value.id, menuIds)
    ElMessage.success('菜单分配成功')
    menuDialogVisible.value = false
  } catch (error) {
    console.error('菜单分配失败:', error)
    ElMessage.error('菜单分配失败')
  }
}

onMounted(() => {
  fetchRoleList()
  fetchMenuTree()
})
</script>

<style lang="scss" scoped>
.roles-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-toolbar {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>